package sctu.edu.java.year2016.team02.project.pc.problem;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;

/**
 * Created by Eoly on 2016/6/18.
 */
//提供各种方法实现对套接字各种错误的提示或解决
public class SocketListener {
    public static int screenWidth=Toolkit.getDefaultToolkit().getScreenSize().width;
    public static int ScreenHeight=Toolkit.getDefaultToolkit().getScreenSize().height;
    private static JDialog connectLog = null;

    //输出一个错误提示框，并以connectedState方法解决；
    public static void outErrorMessage(String text, String title) {
        JOptionPane.showMessageDialog(new JFrame(), text, title, JOptionPane.ERROR_MESSAGE);
        connectedState(text);
    }

    //输出一个警告提示框
    public static void outWorryMessage(String text, String title) {
        JOptionPane.showMessageDialog(new JFrame(), text, title, JOptionPane.WARNING_MESSAGE);
    }

    //输出一个提示框
    public static void outPlainMessage(String text, String title) {
        JOptionPane.showMessageDialog(new JFrame(), text, title, JOptionPane.PLAIN_MESSAGE);
    }

    //检查ip格式
    public static boolean ipCheck(String text) {
        if (text != null && !text.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            return text.matches(regex);
        }
        return false;
    }

    //调用该方法，可以对Socket套接字进行设置
    public static void setSocket(){
        JDialog setS = new JDialog(new JFrame(),"设置服务器接口",true);
        JLabel ipLabel = new JLabel("ip地址+接口:");
        JTextField ipAddress = new JTextField(PcProblem.ipNetAddress);
        JTextField port = new JTextField();
        JButton connect =  new JButton("连接到服务器");
        port.setDocument(new NumberLenghtLimitedDmt(5));
        port.setText(String.valueOf(PcProblem.port));
        ipLabel.setBounds(20, 40, 90, 25);
        ipAddress.setBounds(100, 40, 100, 25);
        port.setBounds(205, 40, 50, 25);
        connect.setBounds(140, 80, 120, 25);
        connect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!ipCheck(ipAddress.getText()) || ipAddress.getText().isEmpty()) {
                    outPlainMessage("ip地址不正确或ip地址为空", "提示");
                } else if (port.getText().isEmpty()) {
                    outPlainMessage("接口不能为空", "提示");
                } else {
                    PcProblem.ipNetAddress = ipAddress.getText();
                    PcProblem.port = Integer.valueOf(port.getText());
                    setS.dispose();
                }
            }
        });
        setS.setBounds(screenWidth/3,ScreenHeight/3,350, 150);
        setS.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        setS.setLayout(null);
        setS.add(ipAddress);
        setS.add(ipLabel);
        setS.add(port);
        setS.add(connect);
        setS.setResizable(false);
        setS.setVisible(true);
    }

    //当与服务端链接错误时，调用该方法会尝试重新连接服务端
    public static void connectedState(String text) {
        JLabel message = new JLabel(text);
        JLabel state = new JLabel("Reconnect.");
        Button cancel = new Button("Cancel&Quit");
        Button reback = new Button("Reback");
        message.setBounds(10, 20, 200, 25);
        state.setBounds(10, 40, 200, 25);
        cancel.setBounds(30, 75, 100, 25);
        reback.setBounds(170,75,100,25);


        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean isConn = false;
                int count = 0;
                while (!isConn) {
                    if (PcProblem.socket != null) {
                        try {
                            PcProblem.socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        PcProblem.socket = new Socket(PcProblem.ipNetAddress, PcProblem.port);
                        PcProblem.socket.setSoTimeout(3000);
                        isConn = true;
                        if (connectLog != null) connectLog.dispose();
                        outPlainMessage("连接" + PcProblem.socket.getInetAddress() + "成功", "连接成功");
                    } catch (IOException e) {
                        message.setText(e.getMessage());
                        state.setText(new String((count++ % 4 < 3) ? (state.getText() + ".") : "Reconnect."));
                        isConn = false;
                    }
                }
            }
        }).start();
        connectLog = new JDialog(new JFrame(), "", true);
        cancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(-1);
            }
        });
        reback.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setSocket();
            }
        });
        connectLog.setBounds(screenWidth / 3, ScreenHeight / 4, 300, 150);
        connectLog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        connectLog.setLayout(null);
        connectLog.add(message);
        connectLog.add(cancel);
        connectLog.add(state);
        connectLog.add(reback);
        connectLog.setResizable(false);
        connectLog.setVisible(true);
    }
}
